<template>
  <div class="blog-view-container">
    <div class="blog-header">
      <h1>{{ blog.title }}</h1>
      <div class="blog-tags" v-if="blog.tags?.length">
        <span v-for="tag in blog.tags" :key="tag" class="tag">
          {{ tag }}
        </span>
      </div>
      <div class="blog-meta">
        <span>作者：{{ getAuthorName(blog) }}</span>
        <span>发布时间：{{ formatDate(blog.approveTime || blog.createTime) }}</span>
        <span>阅读量：{{ blog.views }}</span>
        <span>点赞量：{{ blog.likes?.length || 0 }}</span>
      </div>
    </div>

    <div class="blog-content">
      {{ blog.content }}
    </div>

    <!-- 将点赞移到内容下方，评论区上方 -->
    <div class="interaction-area">
      <div class="like-btn" @click="toggleLike" :class="{ 'liked': isLiked }">
        <i class="fa fa-thumbs-up"></i>
        <span class="like-count">{{ blog.likes?.length || 0 }}</span>
        <span class="like-text">{{ isLiked ? '已赞' : '点赞' }}</span>
      </div>
    </div>

    <!-- 评论区 -->
    <div class="comments-section">
      <h3>评论区</h3>
      <div class="comment-input">
        <textarea 
          v-model="newComment" 
          placeholder="写下你的评论..."
          rows="3"
        ></textarea>
        <button @click="submitComment">发表评论</button>
      </div>

      <div class="comment-list">
        <div v-for="comment in sortedComments" :key="comment.id" class="comment-item">
          <div class="comment-user">
            <img :src="comment.userAvatar || '/default-avatar.png'" alt="avatar">
            <span class="username">{{ getUserNickname(comment.username) }}</span>
            <span class="time">{{ formatDate(comment.time) }}</span>
          </div>
          <div class="comment-content">{{ comment.content }}</div>
          <div class="comment-actions">
            <span class="reply" @click="showReplyInput(comment)">回复</span>
            <span 
              v-if="canDelete" 
              class="delete" 
              @click="deleteComment(comment)"
            >删除</span>
          </div>
          
          <!-- 回复输入框 -->
          <div v-if="comment.showReplyInput" class="reply-input">
            <textarea 
              v-model="comment.replyContent" 
              placeholder="写下你的回复..."
              rows="2"
            ></textarea>
            <div class="reply-actions">
              <button @click="submitReply(comment)">回复</button>
              <button class="cancel" @click="hideReplyInput(comment)">取消</button>
            </div>
          </div>
          
          <!-- 回复列表 -->
          <div v-if="comment.replies?.length" class="reply-list">
            <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
              <div class="reply-user">
                <img :src="reply.userAvatar || '/default-avatar.png'" alt="avatar">
                <span class="username">{{ getUserNickname(reply.username) }}</span>
                <span class="time">{{ formatDate(reply.time) }}</span>
              </div>
              <div class="reply-content">{{ reply.content }}</div>
              <span 
                v-if="canDelete" 
                class="delete-reply" 
                @click="deleteReply(comment, reply)"
              >删除</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="blog-actions">
      <button class="back" @click="$router.push('/blog')">返回列表</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BlogViewComponent',
  data() {
    return {
      blog: {},
      newComment: '',
      currentUser: JSON.parse(localStorage.getItem('currentUser') || '{}')
    }
  },
  computed: {
    isLiked() {
      return this.blog.likes?.includes(this.currentUser.username)
    },
    sortedComments() {
      return [...(this.blog.comments || [])].sort((a, b) => 
        new Date(b.time) - new Date(a.time)
      )
    },
    canDelete() {
      return this.currentUser.isAdmin || this.currentUser.username === this.blog.author
    }
  },
  created() {
    this.loadBlog()
  },
  methods: {
    loadBlog() {
      const blogId = parseInt(this.$route.params.id)
      const blogs = JSON.parse(localStorage.getItem('blogs') || '[]')
      this.blog = blogs.find(b => b.id === blogId) || {}
      
      if (this.blog.id) {
        this.blog.views = (this.blog.views || 0) + 1
        this.saveBlog()
      }
    },
    formatDate(dateString) {
      return new Date(dateString).toLocaleString()
    },
    toggleLike() {
      if (!this.currentUser.username) {
        alert('请先登录')
        return
      }

      if (!this.blog.likes) {
        this.blog.likes = []
      }

      const index = this.blog.likes.indexOf(this.currentUser.username)
      if (index === -1) {
        this.blog.likes.push(this.currentUser.username)
      } else {
        this.blog.likes.splice(index, 1)
      }

      this.saveBlog()
    },
    submitComment() {
      if (!this.currentUser.username) {
        alert('请先登录')
        return
      }

      if (!this.newComment.trim()) {
        return
      }

      if (!this.blog.comments) {
        this.blog.comments = []
      }

      this.blog.comments.push({
        id: Date.now(),
        username: this.currentUser.username,
        userAvatar: this.currentUser.avatarUrl,
        content: this.newComment.trim(),
        time: new Date().toISOString(),
        likes: [],
        replies: []
      })

      this.newComment = ''
      this.saveBlog()
    },
    showReplyInput(comment) {
      if (!this.currentUser.username) {
        alert('请先登录')
        return
      }
      comment.showReplyInput = true
      comment.replyContent = ''
    },
    
    hideReplyInput(comment) {
      comment.showReplyInput = false
      comment.replyContent = ''
    },
    
    submitReply(comment) {
      if (!comment.replyContent?.trim()) {
        return
      }

      if (!comment.replies) {
        comment.replies = []
      }

      comment.replies.push({
        id: Date.now(),
        username: this.currentUser.username,
        userAvatar: this.currentUser.avatarUrl,
        content: comment.replyContent.trim(),
        time: new Date().toISOString()
      })

      this.hideReplyInput(comment)
      this.saveBlog()
    },
    saveBlog() {
      const blogs = JSON.parse(localStorage.getItem('blogs') || '[]')
      const index = blogs.findIndex(b => b.id === this.blog.id)
      if (index !== -1) {
        blogs[index] = this.blog
        localStorage.setItem('blogs', JSON.stringify(blogs))
      }
    },
    deleteComment(comment) {
      if (confirm('确定要删除这条评论吗？')) {
        const index = this.blog.comments.findIndex(c => c.id === comment.id)
        if (index !== -1) {
          this.blog.comments.splice(index, 1)
          this.saveBlog()
        }
      }
    },
    
    deleteReply(comment, reply) {
      if (confirm('确定要删除这条回复吗？')) {
        const replyIndex = comment.replies.findIndex(r => r.id === reply.id)
        if (replyIndex !== -1) {
          comment.replies.splice(replyIndex, 1)
          this.saveBlog()
        }
      }
    },
    getAuthorName(blog) {
      const users = JSON.parse(localStorage.getItem('users') || '[]')
      const author = users.find(user => user.username === blog.author)
      return author?.nickname || blog.author
    },
    getUserNickname(username) {
      const users = JSON.parse(localStorage.getItem('users') || '[]')
      const user = users.find(u => u.username === username)
      return user?.nickname || username
    }
  }
}
</script>

<style lang="scss" scoped>
.blog-view-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;

  .blog-header {
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #eee;

    h1 {
      font-size: 28px;
      color: #333;
      margin-bottom: 15px;
    }

    .blog-meta {
      color: #999;
      font-size: 14px;

      span {
        margin-right: 20px;
        
        &:last-child {
          margin-right: 0;
        }
      }
    }
  }

  .blog-content {
    background: white;
    padding: 30px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
    line-height: 1.8;
    color: #333;
    min-height: 300px;
  }

  .comments-section {
    margin-top: 30px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);

    h3 {
      margin-bottom: 20px;
      color: #333;
    }

    .comment-input {
      margin-bottom: 20px;

      textarea {
        width: 100%;
        padding: 10px;
        border: 1px solid #d9d9d9;
        border-radius: 4px;
        margin-bottom: 10px;
        resize: vertical;

        &:focus {
          outline: none;
          border-color: #40a9ff;
        }
      }

      button {
        padding: 8px 16px;
        background: #1890ff;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;

        &:hover {
          background: #40a9ff;
        }
      }
    }

    .comment-item {
      padding: 15px 0;
      border-bottom: 1px solid #eee;

      .comment-user {
        display: flex;
        align-items: center;
        margin-bottom: 10px;

        img {
          width: 32px;
          height: 32px;
          border-radius: 50%;
          margin-right: 10px;
        }

        .username {
          font-weight: bold;
          margin-right: 10px;
        }

        .time {
          color: #999;
          font-size: 12px;
        }
      }

      .comment-content {
        margin: 10px 0;
        line-height: 1.6;
      }

      .comment-actions {
        font-size: 12px;
        color: #999;

        span {
          cursor: pointer;
          margin-right: 15px;
          
          &:hover {
            color: #1890ff;
          }
          
          &.delete {
            color: #ff4d4f;
            
            &:hover {
              color: #ff7875;
            }
          }
        }
      }

      .reply-list {
        margin-left: 42px;
        margin-top: 10px;
        padding: 10px;
        background: #f9f9f9;
        border-radius: 4px;

        .reply-item {
          padding: 10px 0;
          border-bottom: 1px solid #f0f0f0;
          position: relative;

          &:last-child {
            border-bottom: none;
          }

          .reply-user {
            display: flex;
            align-items: center;
            margin-bottom: 5px;

            img {
              width: 24px;
              height: 24px;
              border-radius: 50%;
              margin-right: 8px;
            }

            .username {
              font-weight: bold;
              margin-right: 10px;
            }

            .time {
              color: #999;
              font-size: 12px;
            }
          }

          .reply-content {
            margin-bottom: 5px;
          }

          .delete-reply {
            position: absolute;
            right: 10px;
            top: 10px;
            font-size: 12px;
            color: #ff4d4f;
            cursor: pointer;
            
            &:hover {
              color: #ff7875;
            }
          }
        }
      }
    }
  }

  .blog-actions {
    margin-top: 20px;
    text-align: center;

    button {
      padding: 8px 16px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      color: white;

      &.back {
        background: #1890ff;
        
        &:hover {
          background: #40a9ff;
        }
      }
    }
  }

  .blog-tags {
    margin: 12px 0;
    display: flex;
    gap: 8px;
    flex-wrap: wrap;

    .tag {
      padding: 4px 12px;
      background: #e6f7ff;
      color: #1890ff;
      border-radius: 16px;
      font-size: 14px;
    }
  }
}

.reply-input {
  margin: 10px 0 10px 42px;
  
  textarea {
    width: 100%;
    padding: 8px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    resize: vertical;
    margin-bottom: 10px;
    
    &:focus {
      outline: none;
      border-color: #40a9ff;
    }
  }
  
  .reply-actions {
    display: flex;
    gap: 10px;
    
    button {
      padding: 6px 12px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      
      &:first-child {
        background: #1890ff;
        color: white;
        
        &:hover {
          background: #40a9ff;
        }
      }
      
      &.cancel {
        background: #f5f5f5;
        color: #666;
        
        &:hover {
          background: #e8e8e8;
        }
      }
    }
  }
}

.interaction-area {
  padding: 20px 0;
  margin: 20px 0;
  border-bottom: 1px solid #eee;
  border-top: 1px solid #eee;
  text-align: center;

  .like-btn {
    display: inline-flex;
    align-items: center;
    padding: 8px 20px;
    border-radius: 24px;
    cursor: pointer;
    transition: all 0.3s ease;
    background: #f5f5f5;
    
    &:hover {
      background: #f0f0f0;
    }
    
    &.liked {
      background: #fff0f0;
      color: #ff4d4f;
      
      i {
        color: #ff4d4f;
      }
      
      .like-count {
        color: #ff4d4f;
      }
    }

    i {
      font-size: 18px;
      margin-right: 8px;
      color: #666;
    }

    .like-count {
      font-weight: bold;
      margin-right: 8px;
      color: #666;
    }

    .like-text {
      font-size: 14px;
      color: #666;
    }
  }
}
</style> 